package com.coolxiaoyao.web;

import com.coolxiaoyao.web.context.NtWebApplicationContext;
import com.coolxiaoyao.web.handler.DefaultExceptionHandler;
import com.coolxiaoyao.web.http.DispatcherServlet;
import com.coolxiaoyao.web.http.Filter;
import com.coolxiaoyao.web.http.HttpServer;
import io.netty.handler.ipfilter.IpFilterRule;

/**
 * @author Kerry on 18/09/20
 */

@SuppressWarnings("AlibabaAvoidManuallyCreateThread")
public class NtingApplication {
    public static void runAsync(final int httpPort, final Class<?> primaryClass, final String... args) {
        runAsync(httpPort, primaryClass, null, null, args);
    }

    public static void runAsync(final int httpPort, final Class<?> primaryClass, IpFilterRule ipFilterRule, final String... args) {
        Thread thread = new Thread(() -> {
            try {
                runSync(httpPort, primaryClass, null, ipFilterRule, args);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        thread.setName("nting-web");
        thread.start();
    }


    public static void runAsync(final int httpPort, final Class<?> primaryClass, Filter filter, IpFilterRule ipFilterRule, final String... args) {
        Thread thread = new Thread(() -> {
            try {
                runSync(httpPort, primaryClass, filter, ipFilterRule, args);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        thread.setName("nting-web");
        thread.start();
    }

    public static void runSync(int httpPort, Class<?> primaryClass, String... args) throws Exception {
        runSync(httpPort, primaryClass, null, null, args);
    }

    public static void runSync(int httpPort, Class<?> primaryClass, Filter filter, IpFilterRule ipFilterRule, String... args) throws Exception {
        NtWebApplicationContext ntWebApplicationContext = new NtWebApplicationContext();
        ntWebApplicationContext.startup(args, primaryClass);

        ntWebApplicationContext.setExceptionHandler(new DefaultExceptionHandler());
        DispatcherServlet dispatcherServlet = new DispatcherServlet(ntWebApplicationContext);
        dispatcherServlet.setFilter(filter);
        // default work count is 1
        HttpServer httpServer = new HttpServer(httpPort, dispatcherServlet, 1);
        httpServer.setIpFilterRule(ipFilterRule);
        httpServer.startNetty();
        Runtime.getRuntime().addShutdownHook(new Thread(httpServer::stopNetty));
    }


}
